package com.mask.boot.controller.file;

import org.apache.commons.fileupload.ProgressListener;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.NumberFormat;


/** 文件上传进度条监控
 * ClassName MyProgressListener
 * Create by hx
 * Date 2020/12/13 下午1:52
 */

public class MyProgressListener implements ProgressListener {
    private HttpSession session;
    public MyProgressListener(HttpServletRequest request){
        session = request.getSession();
    }
    @Override
    public void update(long pBytesRead, long pContentLength, int pItems) {
        //将数据进行格式化
        //已读取数据由字节转换为M
        double readM=pBytesRead/1024.0/1024.0;
        //已读取数据由字节转换为M
        double totalM=pContentLength/1024.0/1024.0;
        //已读取百分百
        double percent=readM/totalM;
        //格式化数据
        //已读取
        String readf=dataFormat(pBytesRead);
        //总大小
        String totalf=dataFormat(pContentLength);
        //进度百分百
        NumberFormat format=NumberFormat.getPercentInstance();
        String progress=format.format(percent);
//        List<String> list = new ArrayList<>();
//        list.add(readf);
//        list.add(totalf);
//        list.add(progress);
//        Gson gson = new Gson();
//        String data = gson.toJson(list);
        //将信息存入session
        session.setAttribute("progress", progress);
        //打印消息到控制台
//        System.out.println("pBytesRead===>"+pBytesRead);
//        System.out.println("pContentLength==>"+pContentLength);
//        System.out.println("pItems===>"+pItems);
//        System.out.println("readf--->"+readf);
//        System.out.println("totalf--->"+totalf);
//        System.out.println("progress--->"+progress);
    }


    public String dataFormat(double data){
        String formdata="";
        if (data>=1024*1024) {//大于等于1M
            formdata=Double.toString(data/1024/1024)+"M";
        }else if(data>=1024){//大于等于1KB
            formdata=Double.toString(data/1024)+"KB";
        }else{//小于1KB
            formdata=Double.toString(data)+"byte";
        }
        return formdata.substring(0, formdata.indexOf(".")+2);
    }

}
